<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    echo json_encode(['success' => false, 'message' => '请求方法不正确']);
    exit;
}

$settlementId = intval($_POST['settlement_id'] ?? 0);
$newAmount = floatval($_POST['new_amount'] ?? 0);
$adjustmentReason = trim($_POST['adjustment_reason'] ?? '');

if ($settlementId <= 0 || $newAmount <= 0) {
    echo json_encode(['success' => false, 'message' => '参数无效']);
    exit;
}

if (empty($adjustmentReason)) {
    echo json_encode(['success' => false, 'message' => '请填写金额调整原因']);
    exit;
}

$db = getDB();

// 获取原金额和结算信息
$stmt = $db->prepare("SELECT total_amount, settlement_info FROM settlements WHERE id = ?");
$stmt->execute([$settlementId]);
$settlement = $stmt->fetch();

if (!$settlement) {
    echo json_encode(['success' => false, 'message' => '结算记录不存在']);
    exit;
}

$oldAmount = $settlement['total_amount'];

// 构建调整备注
$adjustmentNote = "\n\n【金额调整】" . 
                 "\n调整时间：" . date('Y-m-d H:i:s') . 
                 "\n操作人员：" . $_SESSION['username'] .
                 "\n调整原因：" . $adjustmentReason . 
                 "\n原金额：¥" . number_format($oldAmount, 2) . 
                 " → 新金额：¥" . number_format($newAmount, 2);

// 更新结算金额和备注
$newSettlementInfo = $settlement['settlement_info'] . $adjustmentNote;

$stmt = $db->prepare("UPDATE settlements SET total_amount = ?, settlement_info = ?, updated_at = NOW() WHERE id = ?");

if ($stmt->execute([$newAmount, $newSettlementInfo, $settlementId])) {
    echo json_encode(['success' => true, 'message' => '结算金额更新成功']);
    
    // 记录安全日志
    logSecurityEvent('settlement_amount_adjusted', $_SESSION['user_id'], 
        "结算ID: $settlementId, 原金额: $oldAmount, 新金额: $newAmount, 原因: $adjustmentReason");
} else {
    echo json_encode(['success' => false, 'message' => '结算金额更新失败']);
}
?>